package com.smartsoft.fragments;

import android.app.Fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.smartsoft.R;
import com.smartsoft.model.CountryItem;

import java.util.ArrayList;
import java.util.List;


/*
* https://www.google.com.ua/search?q=infinite+listview+android&oq=infinite+ListView&aqs=chrome.1.69i57j0l3.5007j0j7&sourceid=chrome&espv=210&es_sm=122&ie=UTF-8
*
* http://stackoverflow.com/questions/15266732/infinite-scrolling-of-listview-in-android
* */
public class EditContactFragment extends Fragment {
    /**
     * For debug purposes.
     */
    private static final String TAG = "EDIT_CONTACT_FRAGMENT";
    /**
     * For lookuping resource's URI.
     */
    private static final String RESOURCE_PREFIX = "android.resource://";
    /**
     * List of avatar's drawable Ids.
     */
    private static final int[] AVATAR_DRAW_IDS = new int[] {
            R.drawable.neo_png,
            R.drawable.trin_png,
            R.drawable.mor_png
    };

    private ListView mCountryCarousel;
    private CountriesAdapter carouselViewAdapter;

    /**
     * Defines possible scrolling direction for carousel list.
     */
    enum ScrollingDirection {UP, DOWN};

    /**
     * Contains information about each country, which will be
     * displayed in carousel list.
     */
    private static final List<CountryItem> COUNTRIES_INFO = new ArrayList<CountryItem>() {{
        add(new CountryItem("Ukraine", R.drawable.ukraine_flag));
        add(new CountryItem("Canada", R.drawable.canada_flag));
        add(new CountryItem("United Kingdom", R.drawable.uk_flag));
        add(new CountryItem("Germany", R.drawable.germany_flag));
        add(new CountryItem("USA", R.drawable.usa_flag));
        add(new CountryItem("Argentina", R.drawable.argentina_flag));
        add(new CountryItem("Turkey", R.drawable.turcay_flag));
    }};


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View editContactView =  inflater.inflate(R.layout.edit_contact_fragment, container);

        final ViewFlipper mAvatarFlipper = (ViewFlipper) editContactView.findViewById(R.id.avatar_flipper);

        /*
        * Populate view flipper with images. Each image creates
        * from XML definition.
        * */
        for (int i = 0; i < AVATAR_DRAW_IDS.length; i++) {
            ImageView mAvatarImage = (ImageView) inflater.inflate(R.layout.avatar_view_item, container, false);
            mAvatarImage.setImageURI(getResourceUri(AVATAR_DRAW_IDS[i]));
            mAvatarFlipper.addView(mAvatarImage);
        }

        /*
        * Handle "Avatar Forward" and "Avatar Back" actions when user
        * clicks on respective buttons, and perform smooth sliding of images.
        * */
        final Button mAvatarForward = (Button) editContactView.findViewById(R.id.avatar_forward_btn);
        final Button mAvatarBack = (Button) editContactView.findViewById(R.id.avatar_back_btn);
        mAvatarForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAvatarFlipper.setInAnimation(getActivity(), R.anim.view_transition_in_left);
                mAvatarFlipper.setOutAnimation(getActivity(), R.anim.view_transition_out_left);
                mAvatarFlipper.showNext();
            }
        });
        mAvatarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAvatarFlipper.setInAnimation(getActivity(), R.anim.view_transition_in_right);
                mAvatarFlipper.setOutAnimation(getActivity(), R.anim.view_transition_out_right);
                mAvatarFlipper.showPrevious();
            }
        });

        /*
        * Sets up countries list (countries items supplied through ListView's custom adapter)
        * for carousel of countries.
        * */
        mCountryCarousel = (ListView) editContactView.findViewById(R.id.country_carousel_list);
        carouselViewAdapter = new CountriesAdapter(COUNTRIES_INFO, getActivity());
        mCountryCarousel.setAdapter(carouselViewAdapter);
        mCountryCarousel.setSelection(CountriesAdapter.CAROUSEL_MIDDLE_POSITION);

        /*
        * Add ability of scrolling country items
        * */
        Button mPreviousCountry = (Button) editContactView.findViewById(R.id.prev_country_btn);
        mPreviousCountry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToPosition(ScrollingDirection.UP);
            }
        });

        Button mNextCountry = (Button) editContactView.findViewById(R.id.next_country_btn);
        mNextCountry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToPosition(ScrollingDirection.DOWN);
            }
        });
        return editContactView;
    }

    /**
     * Scroll carousel's content to new position depending of
     * the specified direction.
     *
     * @param scrollDirection   direction of the scrolling Up or Down
     */
    private void scrollToPosition(ScrollingDirection scrollDirection) {
        int goToPosition = carouselViewAdapter.getAbsoluteCurrentPosition();
        mCountryCarousel.getSelectedItemPosition();
        goToPosition = scrollDirection == ScrollingDirection.UP ? goToPosition + 1 : goToPosition - 1;
        Log.d(TAG, "Go to position " + goToPosition);
        mCountryCarousel.requestFocusFromTouch();
        mCountryCarousel.setSelectionFromTop(goToPosition, 40);
    }

    /**
     * Get resource URI determined by resIdentifier.
     *
     * @param resIdentifier resource identifier
     * @return URI of the resource
     */
    private Uri getResourceUri(int resIdentifier) {
        StringBuilder resourcePathBuilder = new StringBuilder();
        resourcePathBuilder.append(RESOURCE_PREFIX)
                .append(getActivity().getPackageName())
                .append("/")
                .append(resIdentifier);
        return Uri.parse(resourcePathBuilder.toString());
    }


    /**
     * Adapter for carousel countries ViewList.
     */
    private class CountriesAdapter extends BaseAdapter {
        private static final String TAG = "COUNTRIES_ADAPTER";
        private static final int CAROUSEL_MAX_POSITION = Integer.MAX_VALUE;
        private static final int CAROUSEL_MIDDLE_POSITION = CAROUSEL_MAX_POSITION / 2;

        private int absoluteCurrentPosition = CAROUSEL_MIDDLE_POSITION;
        private int relativeCurrentPosition;
        private List<CountryItem> countryItems;
        private Context context;

        public CountriesAdapter(List<CountryItem> countryItems, Context context) {
//            super(context, R.layout.country_view_item, countryItems);
            this.context = context;
            this.countryItems = countryItems;
        }

        public int getAbsoluteCurrentPosition() {
            return absoluteCurrentPosition;
        }

        public int getRelativeCurrentPosition() {
            return relativeCurrentPosition;
        }


        @Override
        public int getCount() {
            return CAROUSEL_MAX_POSITION;
        }

        @Override
        public CountryItem getItem(int position) {
            relativeCurrentPosition = position % countryItems.size();
            Log.d(TAG, "Relative position is " + relativeCurrentPosition);
            return countryItems.get(relativeCurrentPosition);
        }

        @Override
        public long getItemId(int position) {
            return CAROUSEL_MAX_POSITION;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.d(TAG, "getView() method called at position " + position);
            absoluteCurrentPosition = position;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.country_view_item, parent, false);
            }
            // Setup country's flag image and name.
            ImageView mCountryFlagView = (ImageView) convertView.findViewById(R.id.country_flag_image);
            TextView mCountryNameView = (TextView) convertView.findViewById(R.id.country_name);

            CountryItem countryItem = getItem(position);
            mCountryNameView.setText(countryItem.getCountryName());
            mCountryFlagView.setImageURI(getResourceUri(countryItem.getCountryFlagResId()));

            return convertView;
        }
    }

}
